package com.xhh.fs.controller;

import com.xhh.fs.pojo.Book;
import com.xhh.fs.pojo.Category;
import com.xhh.fs.service.BookService;
import com.xhh.fs.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
public class LibraryController {

    @Autowired
    BookService bookService;

    @Autowired
    CategoryService categoryService;
    // 查出全部书籍
    @GetMapping("api/findAll")
    public List<Book>  findAllBooks(){
        return bookService.findAll();
    }
    // 增加或新增书籍
    @PostMapping("api/ajaxAdd")
    public Book ajaxBooks(@RequestBody Book book){
        bookService.ajax(book);
        return book;
    }
    // 通过ID删除书籍
    @PostMapping("api/delete")
    public void delete(@RequestBody Book book){
        bookService.deleteById(book.getId());
    }
    //搜索栏查询
    @GetMapping("api/search")
    public List<Book> search(@RequestParam("keyWords") String keyWords){
        //关键词为空查询所有
        if(StringUtils.isEmpty(keyWords)){
            return bookService.findAll();
        }else {
            return bookService.search(keyWords);
        }
    }
    // 通过分类ID查询书籍
    @GetMapping("api/categories/{cid}/books")
    public List<Book> findByCategoryId(@PathVariable("cid") int cid){
        if (categoryService.get(cid)!=null){
            return bookService.findByCategory(cid);
        }else {
            return findAllBooks();
        }
    }
    //封面上传
    @PostMapping("api/covers")
    public String coversUpload(MultipartFile file) throws Exception{
        String folder = "D:\\Projects\\From Scratch\\fs\\src\\main\\resources\\templates\\img";
        File imageFolder = new File(folder);
        //对图片进行重命名，但不改变格式
        File f = new File(imageFolder, com.xhh.fs.utils.StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        //图片转换，并返回url
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
